/* Name: Button
 * Author: John Gideon
 * Date: 5-4-12
 * Description: Inherited by buttons, and other objects that can be clicked on, such as planets.
 * Revisions: See Subversion logs at http://code.google.com/p/software-engineering-2012/source/list
 */

public class Button extends Item {
	private Boolean hover = false;
	private Boolean clickState = false;
	protected Boolean selected = false;
	private Boolean isRectangle = true;
	final protected static int BTN_STATE_OFF = 0;
	final protected static int BTN_STATE_HOVER = 1;
	final protected static int BTN_STATE_ON = 2;
	protected int btnDrawState = 0;
	private int btnWidth;
	private int btnHeight;
	
	public Button(){}
	
	// Calculates some variables used in classes that extend this class
	public Button(int px, int py, int pwidth, int pheight) {
		x  = px - (pwidth/2);
		x2 = px + (pwidth/2);
		y  = py - (pheight/2);
		y2 = py + (pheight/2);
		isRectangle = true;
		btnWidth = pwidth;
		btnHeight = pheight;
	}
	
	// Same as above, but used for circular buttons, or when clicking on planets
	public Button(int px, int py, int pr) {
		x = px;
		y = py;
		r = pr;
		isRectangle = false;
	}
	
	// Updates the location of the given button
	public void updateLocation(int px, int py) {
		x  = px - (btnWidth/2);
		x2 = px + (btnWidth/2);
		y  = py - (btnHeight/2);
		y2 = py + (btnHeight/2);
	}
	
	// Updates the given button - sets hover state and click state
	public void updateBtn() {
		hover = mouseInside();
		if (selected || (hover && clickState)) {btnDrawState = BTN_STATE_ON;}
		else if (hover && !selected) {btnDrawState = BTN_STATE_HOVER;}
		else {btnDrawState = BTN_STATE_OFF;}
	}
	
	// Returns whether or not the mouse is within the button
	private Boolean mouseInside() {
		if (isRectangle) {
			return (Mouse.getX() >= x-ViewControl.getX() && Mouse.getX() <= x2-ViewControl.getX()
					&& Mouse.getY() >= y-ViewControl.getY() && Mouse.getY() <= y2-ViewControl.getY());
		} else if (!(this instanceof Planet) || !Fog.mouseIsInside()) {
			return (Math.sqrt(Math.pow(x-ViewControl.mouseX(),2)+Math.pow(y-ViewControl.mouseY(),2)) <= r);
		} else {
			return false;
		}
	}
	
	// Called when button pressed with left mouse button. Event only occurs if mouse is over the given button.
	public void leftMousePressBtn(){
		if (hover) {
			clickState = true;
		}
	}
	
	// Occurs when mouse released
	public void leftMouseReleaseBtn(){
		if (clickState && hover) {
			if (selected) {
				selected = false;
				released();
			} else {
				selected = true;
				pressed();
			}
		}
		clickState = false;
	}
	
	protected void pressed() {}
	protected void released() {}
	public void setSelected(Boolean val) {
		selected = val;
	}
}